<?php

/**
* @desc Просмотр ответов по вопросу.
* 
*/
class Tests_Backend_Questions_Answers extends Backend_Component_List 
{
    
    /**
     * Путь к файлу шаблона.
     *
     * @var string
     */
    protected $_template = 'tests/backend/answers/list.tpl';
    
    /**
     * Описание первичного ключа таблицы.
     *
     * @var mixed
     */
    protected $_key = 'id';
    
    /**
     * Наименования колонок списка.
     *
     * @var array
     */
    protected $_columns = array('answer', 'right', 'action');
    
    /**
     * Наименование поля, по которому нужно упорядочивать записи.
     *
     * @var string
     */
    protected $_order = 'answer';
    
    
    /**
     * Формирует запрос выборки записей страницы.
     *
     * @return  string
     */
    protected function _getQueryBody()
    {
        Application::getResponse()->setTitle(Tests_Utils::_getQuestion());
        
        $query = 'SELECT SQL_CALC_FOUND_ROWS
                         `id`,
                         `answer`, 
                         `right`, 
                         "action"
                    FROM
                         `tests_answers` 
                   WHERE 
                         `question_id` = ' . Application::getRequest()->get('id') . '
                         ' . $this->_getOrder();
        return $query;
    }
    
    protected function _process() 
    {
        if ($_POST) {
            $this->_save();
        }
        
        parent::_process();
                        
        $entries = database::fetchAll($this->_getQueryBody());
        foreach ($entries as &$entry) {
            $entry['url'] = array('answer' => $entry['id']);
        }
        Application::getResponse()->assign(array(
            'entries' => $entries, 
            'add_answer' => array(
                'id' => Application::getRequest()->get('id'), 
                'test' => Application::getRequest()->get('test') ? Application::getRequest()->get('test') : 1, 
                ), 
        ));
        
    }
    
    private function _save() 
    {
        foreach ($_POST['answers'] as $id => $answer) {
            database::update(
                'tests_answers', 
                array('answer' => $answer, 'right' => (isset($_POST['right'][$id]) ? 1 : 0)), 
                array('id' => $id)
                );
        }
        
        $this->_location('?' . str_replace('answers', 'list', $_SERVER['QUERY_STRING']));
    } 
    
}